#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 12-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;

using Thn;
using Thn.Interface.Vcl;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// Defautl implementation of <see cref="IPage"/>.
    /// </summary>
    //[ToolboxItem(false)]
#if DEBUG
    public
#else
    public
#endif
 abstract class PageBase : ControlBase, IPage
    {
        #region Fields
        /// <summary>
        /// Reference to the last page show request.
        /// </summary>
        PageShowContext mLastPageShowRequest = null;        
        #endregion

        #region Properties

        #region Manager
        private IPageManager mManager;
        /// <summary>
        /// Gets/Sets the manager that is currently showing this page.
        /// </summary>
        public IPageManager Manager
        {
            get { return mManager; }
        }
        #endregion

        #region Descriptor
        private IPageDescriptor mDescriptor;
        /// <summary>
        /// Gets the descriptor of this page.
        /// </summary>
        public IPageDescriptor Descriptor
        {
            get { return mDescriptor; }
        }
        #endregion

        #region Render Context
        private PageBaseRenderContext mRenderContext = new PageBaseRenderContext();
        /// <summary>
        /// Gets reference to current renderation context.
        /// </summary>
        protected PageBaseRenderContext RenderContext
        {
            get
            {
                if (mRenderContext == null) mRenderContext = CreateRenderContext();
                #region Defensive tracing
                else
                {
                    //already created
                }
                #endregion

                return mRenderContext;
            }
        }
        #endregion

        #endregion

        #region Events

        #region Shown
        /// <summary>
        /// This event is raised after this page is shown.
        /// </summary>
        public event PageShownHandler Shown;

        /// <summary>
        /// Invoke event Shown
        /// </summary>
        protected void RaiseShown(PageShowContext context)
        {
            PageShownHandler handler = Shown;
            if (handler != null) handler(mManager, context);
        }
        #endregion

        #region Hidden
        /// <summary>
        /// This event is raised after this page is hidden.
        /// </summary>
        public event PageEventHandler Hidden;

        /// <summary>
        /// Invoke event Hidden
        /// </summary>
        protected void RaiseHidden()
        {
            PageEventHandler handler = Hidden;
            if (handler != null) handler(mManager, mDescriptor);
        }
        #endregion

        #endregion

        #region On Shown
        /// <summary>
        /// The method is invoked when this page is displayed to user.
        /// </summary>
        /// <param name="parameters">Optional parameters for showing.</param>
        protected virtual void OnShown(params object[] parameters) { }
        #endregion

        #region On Hidden
        /// <summary>
        /// This method is invoke when this page is hidden.
        /// </summary>
        protected virtual void OnHidden() { }
        #endregion

        #region On Allow Navigation Away
        /// <summary>
        /// Checks to see if user can navigate away from this page.
        /// <para>If return false, this page should call ResumeLastNavigateRequest() to permit last request.</para>
        /// </summary>
        /// <returns>True if allowed, false otherwise.</returns>
        protected virtual bool OnAllowNavigationAway()
        {
            return true;
        }
        #endregion

        #region Process Allow View
        /// <summary>
        /// Checks whether the current user is authorized to view this page.
        /// </summary>
        /// <param name="redirection">When returned result is false. This page may use the redirection as
        /// ID of the page the user will be redirected to.</param>
        public virtual bool ProcessAllowView(ref string redirection)
        {
            return true;
        }
        #endregion

        #region On Get Render Context
        /// <summary>
        /// Get reference to the renderation context which is used by <see cref="IControlRenderer"/>.
        /// </summary>
        protected override RenderContext OnGetRenderContext(Graphics canvas)
        {
            return RenderContext;
        }
        #endregion

        #region Create Render Context
        /// <summary>
        /// Create a new render context customized for this page.
        /// </summary>
        protected virtual PageBaseRenderContext CreateRenderContext()
        {
            return new PageBaseRenderContext();
        }
        #endregion

        #region Resume Last Navigate Request
        /// <summary>
        /// When OnValidate() returns false and decide to allow page navigation later on,
        /// this method should be called.
        /// </summary>
        protected virtual void ResumeLastNavigateRequest()
        {
            if (mLastPageShowRequest != null)
            {
                mLastPageShowRequest.PermissionRequired = false;

            }
            #region Defensive tracing
            else
            {

            }
            #endregion
        }
        #endregion

        #region IPage Members

        #region Show
        /// <summary>
        /// The page manager will call this interface to let a page know it has been shown.
        /// </summary>        
        /// <param name="man">The manager that currently shows this page</param>
        /// <param name="context">Context of show request.</param>
        void IPage.Show(IPageManager man, PageShowContext context)
        {
            mManager = man;
            mDescriptor = context.Descriptor;

            //pass control to my descendants in case they need it
            OnShown(context.Parameters);

            //raise event in case some coder need it but they don't want to inherit from me            
            RaiseShown(context);
        }
        #endregion

        #region Translate
        //bool mTranslateRequired = false;

        //#region Translate
        ///// <summary>
        ///// Requests this control to translate itself using current language
        ///// </summary>
        //protected virtual void OnTranslate()
        //{
        //    //translate myself first
        //    if (mTranslateID != "")
        //    {
        //        string text = Language.Translation.Translate(mTranslateID, mTranslateGroup, null, null);
        //        if (text == "")
        //        {
        //            if (DesignMode) this.Text = "[" + mTranslateID + "]";
        //            else this.Text = mTranslateID;
        //        }
        //        else this.Text = text;
        //    }

        //    //iterate through all of my child and request them to translate themselves
        //    if (this.Controls != null)
        //    {
        //        for (int i = 0; i < Controls.Count; i++)
        //        {
        //            Control child = Controls[i];
        //            if (child is ControlBase) ((ControlBase)child).Translate();
        //            else if (child is Panel) ((Panel)child).Translate();
        //            else if (child is PageBase) ((PageBase)child).Translate();
        //        }
        //    }
        //}

        /// <summary>
        /// Requests this page to translate its content using Translation Service
        /// </summary>
        public void Translate()
        {
            //OnTranslate();
            //mTranslateRequired = false;
        }
        //#endregion

        //#region TranslateGroup
        //private string mTranslateGroup = "";
        ///// <summary>
        ///// Gets/Sets message Group for translation
        ///// </summary>
        //[Browsable(true), DefaultValue(""), Category("Translation"), Description("GroupID for translation")]
        //public string TranslateGroup
        //{
        //    get { return mTranslateGroup; }
        //    set 
        //    { 
        //        mTranslateGroup = value;
        //        if (mTranslateID != "") Translate();
        //    }
        //}
        //#endregion

        //#region TranslateID
        //private string mTranslateID = "";
        ///// <summary>
        ///// Gets/Sets ID of message for translation
        ///// </summary>
        //[Browsable(true), DefaultValue(""), Category("Translation"), Description("ID of message for translation")]
        //public string TranslateID
        //{
        //    get { return mTranslateID; }
        //    set
        //    {
        //        mTranslateID = value;
        //        mTranslateRequired = true;
        //        if (DesignMode) Translate();
        //    }
        //}
        //#endregion

        #endregion

        #region Allow Navigation Away
        /// <summary>
        /// This method is invoked before the manager try to navigate away from current page.
        /// By handling this notification, the page has a chance to cancel the navigation.
        /// </summary>
        /// <returns>True if allowed, false otherwise.</returns>
        bool IPage.AllowNavigationAway(PageShowContext context)
        {
            bool result = OnAllowNavigationAway();
            if (result)
            {
                #region Validation passed
                mLastPageShowRequest = null;
                #endregion
            }
            else
            {
                #region Validation failed, prepare for ResumeLastNavigateRequest() later on
                mLastPageShowRequest = context;
                #endregion
            }

            return result;
        }
        #endregion

        #region Allow View
        /// <summary>
        /// Checks whether the current user is authorized to view this page.
        /// </summary>
        /// <param name="redirection">When returned result is false. This page may use the redirection as
        /// ID of the page the user will be redirected to.</param>
        bool IPage.AllowView(ref string redirection)
        {
            return ProcessAllowView(ref redirection);
        }
        #endregion

        #region Notify Hide
        /// <summary>
        /// This method is called by an <see cref="IPageManager"/> to let this page know that it
        /// is about to be hidden.
        /// </summary>
        void IPage.NotifyHide()
        {
            OnHidden();
            RaiseHidden();
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        public PageBase()
        { }
        #endregion
    }
}
